use std::{env::var, process::Command};

use wtask_base::{app::get_wtask_root_dir, cmd::run_cmd_pure, error::WResult, export::{log_debug, log_info}};


pub(crate) fn stop_exe(name: &str) -> WResult<()> {
    let pids = run_cmd_pure(vec!["pgrep", name], None, None)?;
    for pid in pids.split("\n") {
        run_cmd_pure(vec!["kill", "-2", pid.trim()], None, None)?;
    }
    Ok(())
}

/// sed -i '/wtask/d' ~/.bashrc
/// echo "export WTASK_ROOT=${wtask_root}" >> ~/.bashrc
/// echo "export PATH=\$PATH:${wtask_root}/bin" >> ~/.bashrc
pub(crate) fn add_envs() -> WResult<()> {
    let p_shell = format!("{}/.{}rc", var("HOME").unwrap(), var("SHELL").unwrap().rsplit_once("/").unwrap().1);
    log_info!("Add env to {p_shell} ...");
    log_debug!("Remove old env ...");
    run_cmd_pure(vec!["sed", "-i", "/wtask_install/d", &p_shell], None, None)?;
    let root = get_wtask_root_dir().to_string_lossy().to_string();
    log_debug!("Add new env ...");
    let _child = Command::new("sh")
        .args([
            "-c".to_owned(),
            format!("echo \"export WTASK_ROOT={root} # wtask_install\nexport PATH=\\$PATH:\\${{WTASK_ROOT}}/bin # wtask_install\" >> {p_shell}")
        ])
        .output()?;

    Ok(())
}


